package com.incon.common.interceptor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

public class MyFilterSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private static Logger logger = Logger.getLogger(MyFilterSecurityMetadataSource.class);

    public List<ConfigAttribute> getAttributes(Object object) {
        FilterInvocation fi = (FilterInvocation) object;
        HttpServletRequest request = fi.getRequest();
        String requestUrl = fi.getRequest().getRequestURI();
        List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>();
        // 所有URL对应的角色，应用启动就存放到静态资源里，得到的结果是：不同的URL下，包含的多个角色
        System.out.println(requestUrl);
        Map<String, String> resRoles =new HashMap<String, String>();// Constant.URL_ROLES;
        System.out.println("加载权限"+this.getClass().getSimpleName());
        resRoles.put("/abc","ROLE_USER,ROLE_ADMIN" );
        resRoles.put("/bcd","ROLE_ADMIN" );
        for (Map.Entry<String, String> ent : resRoles.entrySet()) {
            String url = ent.getKey();
            String roles = ent.getValue();

            //根据业务写自己的匹配逻辑
          if(requestUrl.endsWith(url)){
                attributes.addAll(SecurityConfig.createListFromCommaDelimitedString(roles));
           }
        }
        logger.debug("【"+request.getRequestURI()+"】 roles: "+attributes);
        return attributes;
    }


    public Collection<ConfigAttribute> getAllConfigAttributes() {

                    return null;
    }

    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}